from rest_framework import serializers
from .models import Article
from apps.system.serializers import CategorySerializer


class ArticleSerializer(serializers.ModelSerializer):
    author = serializers.CharField(read_only=True)  # read_only 定义只读,创建时就不用传入
    status = serializers.CharField(source='get_status_display', read_only=True)  # :get_status_display  翻译get_xx_display
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)
    category_name = serializers.CharField(source='category.name',read_only=True)
    tags_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Article
        fields = '__all__'

    # def validate(self, attrs):
    #     pass

    def create(self, validated_data):
        print('serializers_create')
        # print(self.initial_data)   获取初始化数据
        validated_data['author'] = self.context['request'].user  # 获取rquest对象
        instance = super(ArticleSerializer, self).create(validated_data)
        return instance

    def get_tags_name(self, obj):
        tag_serializer = CategorySerializer(obj.tags, many=True)
        return tag_serializer.data
